package com.china08.yxyapi.api.manage.sch.platform.website.article;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.sws.SwsSection;
import com.china08.yxyapi.entity.mg.sws.SwsArticle;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.repository.db.SwsSectionRepository;
import com.china08.yxyapi.repository.mg.SwsArticleRepository;

import io.swagger.annotations.ApiOperation;

@CrossOrigin
@RestController
public class ArticeBanchUpdateSectionController extends YxyApiBaseController {

    @Autowired
    SwsSectionRepository swsSectionRepository;

    @Autowired
    SwsArticleRepository swsArticleRepository;

    @ApiOperation("")
    @RequestMapping(value = "/api_yw/manage/sch/platform/website/article/banch/update/section", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void precess(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel) {

        String section1Id = reqModel.section1Id;
        String section2Id = reqModel.section2Id;
        List<String> articeIds = reqModel.articeIds;
        String schoolId = getProfile(request, response).getSchoolId();

        // 判断是否有二级栏目
        List<SwsSection> swsSection2List = swsSectionRepository.findBySchoolIdAndPidOrderByOrderNumAsc(schoolId, section1Id);

        // 有二级栏目，并且没有选择二级栏目
        if (StringUtils.isBlank(section2Id) && swsSection2List.size() > 0) {
            Assert.isTrue(false, "二级栏目不能为空");
        }

        for (String id : articeIds) {
            SwsArticle swsArticle = swsArticleRepository.findById(id);
            if (swsArticle != null) {
                swsArticle.setSection1Id(section1Id);
                swsArticle.setSection2Id(section2Id);
                swsArticleRepository.save(swsArticle);
            }
        }

    }

    protected static class ReqModel extends YxyApiPageReqModel {
        public String section1Id;
        public String section2Id;
        public List<String> articeIds;

        @Override
        public void autoCheck() {
            Assert.isTrue(StringUtils.isNotBlank(section1Id), "一级栏目不能为空");
            Assert.isTrue(articeIds.size() > 0, "请选择要移动的文章");
        }
    }
}
